import echarts from "echarts";
import zrender from "zrender";
import { toRad } from "../utils";
import { animateRotate } from "./base";


const elements = {};

function draw(chart, percentage) {
  let option = {
    angleAxis: {
      max: 100,
      show: false
    },
    radiusAxis: {
      show: false,
      type: "category",
    },
    polar: {
      radius: ['70%', '90%']
    },
    tooltip: {
      show: false
    },
    legend: {
      show: false
    },
    series: [
      {
        type: 'gauge',
        detail: {
          show: false,
          formatter: '{value}%'
        },
        startAngle: 0,
        endAngle: 360,
        axisLine: {
          show: false,
        },
        radius: '70%',
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        axisTick: {
          lineStyle: {
            color: '#526481'
          }
        }
      },
      {
        name: 'a',
        type: 'bar',
        coordinateSystem: 'polar',
        roundCap: true,
        barWidth: 2,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '40',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          color: '#025F68'
        },
        showBackground: true,
        data: [100]
      },
    ]
  };


  chart.setOption(option);
  drawCircle(chart, percentage);
  drawArc(chart, 0, 60);
  drawArc(chart, 180, 240);
}

function drawCircle(chart, percentage) {
  let gradient = new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
    { offset: 0, color: "rgba(0, 0, 0, 0)" },
    { offset: 1, color: "rgba(0, 138, 175, 0.5)" }
  ]);
  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;
  let circle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 40
    },
    style: {
      fill: gradient,
      fillOpacity: 0.5,
      // stroke: "#009adb",
      lineWidth: 1,
      text: percentage + '%',
      fontSize: "20",
      textFill: "#15EFDF"
    }
  });
  zr.add(circle);
  elements.circle = circle;
}

function drawArc(chart, startAngle, endAngle) {
  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;
  let arc = new zrender.Arc({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 40,
      startAngle: toRad(startAngle),
      endAngle: toRad(endAngle),
    },
    style: {
      fill: null,
      stroke: '#02646C',
      lineWidth: 3
    }
  });
  animateRotate(arc);
  zr.add(arc)
}

function update(percentage) {
  elements.circle.attr({
    style: {
      text: percentage + '%',
    }
  });
}

export default {
  draw,
  update
}
